package cn.wangxl.vertx.starter.web.auth;

import io.vertx.core.Handler;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.jwt.JWTAuth;
import io.vertx.ext.auth.jwt.impl.JWTUser;
import io.vertx.ext.web.RoutingContext;

/**
 * @Description 自定义jwt认证
 * @Classname JWTCheckHandler
 * @Created by wangxl
 * @Date 2020/5/10 17:22
 */

public class JWTCheckHandler implements Handler<RoutingContext> {

  // 认证授权(根据需求配置不同的认证方式)
  JWTAuth authProvider = null;

  @Override
  public void handle(RoutingContext routingContext) {
    String jwt = routingContext.request().getHeader("jwt");
    // 使用jwt进行认证
    authProvider.authenticate(new JsonObject().put("jwt", jwt), auth -> {
      if (auth.succeeded()) {
        JWTUser user = (JWTUser) auth.result();
        JsonObject authData = user.principal(); // 这里就是token中解析的数据
//        System.out.println(authData.getString("username"));
//        System.out.println(authData.getString("password"));
        System.out.println("认证成功");
        routingContext.next();
      } else {
        System.out.println("认证失败");
        routingContext.response().setStatusCode(401);
        routingContext.response().end("请先登录");
      }
    });
  }

  public JWTCheckHandler(JWTAuth authProvider) {
    this.authProvider = authProvider;
  }
}
